/********************************************************************************
 *      Copyright:  (C) 2023 LXC
 *                  All rights reserved.
 *
 *       Filename:  get_temp.c
 *    Description:  This file get temperature.
 *
 *        Version:  1.0.0(07/05/23)
 *         Author:  Lin XinCheng <1481155734@qq.com>
 *      ChangeLog:  1, Release initial version on "07/05/23 19:14:01"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>

#include "logger.h"

int get_temp(float *temp)
{
	if( NULL == temp )
	{
		LOGGER_ERROR("Invalid input argument");
		return -1;
	}
	char		 	 dev_path[128] = "/sys/bus/w1/devices/";	
	DIR				*dev_pathfd = NULL;							
	struct dirent	*dev_dir = NULL;							
	char		 	 chip_name[128] = {0};						
	char		 	 dev_name[128] = "w1_slave";				
	int		 		 fd = -1;									
	char		 	 buf[128] = {0};							
	char			*data = NULL;								
	int 		 	 found_flag = 0;							
	int		 		 n = 0;										

	/*打开设备路径*/
	if( NULL == (dev_pathfd = opendir(dev_path)) )
	{
		LOGGER_ERROR("open dev_path failure: %s", strerror(errno));
		return -1;
	}
	LOGGER_DEBUG("Open dev_path: \"%s\" successfully.\n", dev_path);

	/*读取设备的信息*/
	if( NULL == (dev_dir = readdir(dev_pathfd)) )
	{
		LOGGER_ERROR("Read dev_dir failure: %s", strerror(errno));
		return -2;	
	}
	while( NULL != (dev_dir = readdir(dev_pathfd)) )
	{
		
		if( strstr(dev_dir->d_name, "28-") )
		{
			strncpy(chip_name, dev_dir->d_name, sizeof(chip_name));
			found_flag = 1;
		}	
	}
	if( !found_flag )
	{
		LOGGER_ERROR("read dev_dir failure: %s", strerror(errno));
		return -3;	
	}

	/*生成设备的完整路径*/
	strncat(dev_path, chip_name, (sizeof(dev_path) - strlen(dev_path)));
	strncat(dev_path, "/w1_slave", (sizeof(dev_path) - strlen(dev_path)));
	LOGGER_DEBUG("The full path is: \"%s\"\n", dev_path);

	closedir(dev_pathfd);

	/*打开设备的完整路径和文件*/
	if( (fd = open(dev_path, O_RDONLY)) < 0 )
	{
		LOGGER_ERROR("open full path and file failure: %s", strerror(errno));
		return -4;
	}

	/*读取设备文件*/
	if( (n = read(fd, buf, sizeof(buf))) < 0 )
	{
		LOGGER_ERROR("read the file failure: %s", strerror(errno));
		return -5;
	}

	/*获取温度*/
	if( NULL == (data = strstr(buf, "t=")) )
	{
		LOGGER_ERROR("get temperature failure: %s", strerror(errno));
		return -6;
	}
	data += 2;
	*temp = atof(data)/1000;
	LOGGER_DEBUG("get_temp successfully: %f", *temp);

	close(fd);
	return 0;	
}